import { InputNumber, Input, Image, Select, Button, Modal, Message } from '@arco-design/web-react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { ICON_PATHS } from '@/assets/images/constants';
import { generateRandomColor, getFileNameParts, formatDateTime } from '@/utils/common';
import styles from './voiceUploadMake.module.scss';

import MlsAudio from '@/components/common/mlsAudio';
import MlsModal from '@/components/common/mlsModal';
import MlsUpload from '@/components/common/mlsUpload';
import { voiceCombine, multiChannelSplit } from '@/api/audio';
import sharedWebSocket from '@/services/sharedWebSocket.jsx';
import { useLoading } from '@/components/common/mlsLoading/laodingText';

// 音频通道选项
const AUDIO_CHANNELS = [
  { value: '1', label: '单通道' },
  { value: '2', label: '双通道' },
];

export default function VoiceUploadMake({ onNextStep }) {
  const [roleNum, setRoleNum] = useState(3);
  // 创建一个角色名称数组，确保每个元素都有初始值
  const [roleNames, setRoleNames] = useState([]);
  // 新增：创建角色颜色数组，存储每个角色对应的颜色
  const [roleColors, setRoleColors] = useState([]);
  const [uploadedAudioList, setUploadedAudioList] = useState(new Set());
  const [sucessUploadFile, setSuccessUploadFile] = useState({});

  const [qualityValue, setQualityValue] = useState('');
  // 新增：音频通道选择相关状态
  const [showChannelModal, setShowChannelModal] = useState(false);
  const [selectedChannel, setSelectedChannel] = useState('1');

  // 新增：用于存储上一次roleNames状态的ref
  const prevRoleNamesRef = useRef(roleNames);

  const [inputValues, setInputValues] = useState([]);
  const { showLoading, hideLoading } = useLoading();

  // 组件首次加载时初始化角色名称数组和颜色数组
  useEffect(() => {
    const initialNames = [];
    const initialColors = [];

    for (let i = 0; i < 3; i++) {
      initialNames.push(`麦克风${i + 1}`);
      // 首次加载时生成不重复的随机颜色
      initialColors.push(generateRandomColor([], i));
    }

    setRoleNames(initialNames);
    setRoleColors(initialColors);
    setInputValues(initialNames);
  }, []); // 空依赖数组，只在组件首次加载时执行

  // 当角色数量变化时，更新角色名称数组，但保留已有值
  useEffect(() => {
    setRoleNames(prevNames => {
      const updatedNames = [...prevNames];

      // 如果角色数量增加，为新增的位置设置默认名称
      if (roleNum > prevNames.length) {
        for (let i = prevNames.length; i < roleNum; i++) {
          updatedNames.push(`麦克风${i + 1}`);
        }
      }
      // 如果角色数量减少，只保留相应数量的角色名称
      else if (roleNum < prevNames.length) {
        return updatedNames.slice(0, roleNum);
      }

      return updatedNames;
    });

    // 同步更新颜色数组
    setRoleColors(prevColors => {
      const updatedColors = [...prevColors];

      // 如果角色数量增加，为新增的位置生成随机颜色（不与已有颜色重复）
      if (roleNum > prevColors.length) {
        for (let i = prevColors.length; i < roleNum; i++) {
          updatedColors.push(generateRandomColor(updatedColors, i));
        }
      }
      // 如果角色数量减少，只保留相应数量的角色颜色
      else if (roleNum < prevColors.length) {
        return updatedColors.slice(0, roleNum);
      }

      return updatedColors;
    });
  }, []);

  // 当roleNames变化时同步更新inputValues
  useEffect(() => {
    setInputValues(roleNames);
  }, [roleNames]);


  // 处理角色名称变化
  const handleInputChange = (index, value) => {
    const trimmedValue = value.trim();

    // 更新输入框的临时值
    setInputValues(prev => {
      const newValues = [...prev];
      newValues[index] = value;
      return newValues;
    });
  };

  const handleRoleNameConfirm = (index, value) => {
    const trimmedValue = value.trim();

    // 检查是否为空
    if (!trimmedValue) {
      Message.warning('名称不能为空');
      // 恢复原值
      setInputValues(prev => {
        const newValues = [...prev];
        newValues[index] = roleNames[index];
        return newValues;
      });
      return;
    }
    // 检查是否重复
    const isDuplicate = roleNames.some((name, i) => {
      return i !== index && name === trimmedValue;
    });

    if (isDuplicate) {
      Message.error('名称已存在，请输入其他名称');
      // 恢复原值
      setInputValues(prev => {
        const newValues = [...prev];
        newValues[index] = roleNames[index];
        return newValues;
      });
      return;
    }

    // 如果验证通过，更新正式的角色名称
    const newRoleNames = [...roleNames];
    newRoleNames[index] = trimmedValue;
    setRoleNames(newRoleNames);
  }

  // 新增：处理通道选择确认
  const handleChannelConfirm = channel => {
    console.log('clickChannel', channel);
    if (channel === '2') {
      // 多通道拆分
      showLoading('拆分中...');
      multiChannelSplit({
        audioUrl: sucessUploadFile.url,
        audioName: sucessUploadFile.name,
      }).then(res => {
        console.log('multiChannelSplit', res);
        if (res.code === 200) {
        } else {
          Message.error('拆分失败');
          hideLoading();
        }
      }).catch(err => {
        console.log('multiChannelSplit', err);
        Message.error('拆分失败');
        hideLoading();
      })
    } else {
      setUploadedAudioList(new Set([...uploadedAudioList, sucessUploadFile]));
    }

    // 关闭弹窗
    setShowChannelModal(false);
  };

  const clickChannel = channel => {
    setSelectedChannel(channel);
    handleChannelConfirm(channel);
  };

  const fileSuccess = fileObj => {
    let obj = {
      name: fileObj.name,
      url: fileObj.url,
      micType: '',
    };
    console.log('fileSuccess', obj);
    setSuccessUploadFile(fileObj);
    setShowChannelModal(true);
  };

  const fileUploadError = ({ file, error }) => {
    console.log('fileUploadError', error);
  };

  const handleMicTypeChange = (index, micType) => {
    const audioArray = Array.from(uploadedAudioList);

    if (audioArray[index]) {
      audioArray[index] = {
        ...audioArray[index],
        micType: micType,
      };

      setUploadedAudioList(new Set(audioArray));
    }
  };

  const handleMake = useCallback(() => {
    console.log('handleMake', uploadedAudioList);
    // 校验micType是否为空
    const audioArray = Array.from(uploadedAudioList);
    if (!audioArray.length) {
      Message.error('请上传音频');
      return;
    }
    for (let i = 0; i < audioArray.length; i++) {
      if (!audioArray[i].micType) {
        Message.error(`第${i + 1}个音频未选择麦克风类型`);
        return;
      }
    }
    const obj = {
      roleSize: roleNum,
      audioList: Array.from(uploadedAudioList).map(item => ({
        audioName: item.name.slice(0, item.name.lastIndexOf('.')),
        audioUrl: item.url,
        micType: item.micType,
      })),
    }
    showLoading('制作中...');
    voiceCombine(obj).then(res => { 
      console.log('voiceCombine', res);
      if (res.code === 200) {
        // onNextStep();
      }
    }).catch(err => {
      console.log('voiceCombine', err);
      Message.error('合并失败');
      hideLoading();
    })
  });

  const handleDelete = (action, src) => {
    console.log(src);
    // 根据src删除
    const audioArray = Array.from(uploadedAudioList);
    const updatedAudioList = audioArray.filter(item => item.url !== src);
    setUploadedAudioList(new Set(updatedAudioList));
  }

  // 新增：监听roleNames变化，同步更新uploadedAudioList中对应的micType
  useEffect(() => {
    // 当组件首次加载时不执行更新逻辑
    if (roleNames.length === 0) return;

    // 获取之前的roleNames引用（使用ref来存储）
    if (prevRoleNamesRef.current.length > 0) {
      // 将Set转换为数组进行操作
      const audioArray = Array.from(uploadedAudioList);
      let hasChanges = false;

      // 遍历当前所有音频项
      for (let i = 0; i < audioArray.length; i++) {
        const audioItem = audioArray[i];
        const currentMicType = audioItem.micType;

        // 如果当前音频项有micType值
        if (currentMicType) {
          // 查找该micType在之前roleNames中的索引
          const oldIndex = prevRoleNamesRef.current.indexOf(currentMicType);

          // 如果找到了匹配项，说明这个角色名称被修改了
          if (oldIndex !== -1 && roleNames[oldIndex] !== currentMicType) {
            // 更新micType为新的角色名称
            audioArray[i] = {
              ...audioItem,
              micType: roleNames[oldIndex],
            };
            hasChanges = true;
          }
        }
      }

      // 如果有变化，则更新uploadedAudioList
      if (hasChanges) {
        setUploadedAudioList(new Set(audioArray));
      }
    }

    // 保存当前的roleNames引用，供下次比较使用
    prevRoleNamesRef.current = [...roleNames];
  }, [roleNames, uploadedAudioList]);

  useEffect(() => {
    const handleOpt = data => {
      console.log('socket result:', data);
      if (data.func === 'split_audio_channel_success') {
        // 多通道拆分
        let list = data.data || [];

        const { name, extension } = getFileNameParts(sucessUploadFile.name);
        list = list.map((item, index) => {
          return {
            url: item,
            name: `${name}_${index + 1}${extension}`,
          };
        });
        setUploadedAudioList(new Set([...uploadedAudioList, ...list]));
        hideLoading();
      }
      if (data.func === 'split_audio_channel_fail') {
        Message.error('拆分失败');
        hideLoading();
      }
      if (data.func === 'audio_merge_success') {
        // 音频合并 将返回的data.data传送给下一个页面
        hideLoading();
        onNextStep(data.data);
      }
      if (data.func === 'audio_merge_fail') {
        // 音频合并
        Message.error('合并失败');
        hideLoading();
      }
    };
    sharedWebSocket.on('resp', handleOpt);
    return () => {
      sharedWebSocket.off('resp', handleOpt);
    };
  }, [sucessUploadFile]);

  return (
    <div className={styles.dubbingMakePage}>
      <div className={styles.dubbingMakePageTitle}>
        <span>音频输入</span>
        <span className={styles.date}>
          {formatDateTime('YYYY/MM/DD')}
          <Image
            className={styles.dateIcon}
            src={ICON_PATHS.RETREAT_ICON}
            preview={false}
            draggable={false}
          />
        </span>
      </div>
      <div className={styles.opBox}>
        <div className={styles.roleNum}>
          <span>角色数量</span>
          <InputNumber
            mode="button"
            defaultValue={roleNum}
            max={3}
            step={1}
            min={1}
            className={styles.roleNumInput}
            onChange={setRoleNum} // 添加onChange处理函数
          />
        </div>
        <div className={styles.roleName}>
          {roleNames.map((name, index) => (
            <Input
              key={index}
              mode="button"
              value={inputValues[index] || name}
              onChange={value => handleInputChange(index, value)}
              onBlur={() => handleRoleNameConfirm(index, inputValues[index] || name)}
              onPressEnter={() => handleRoleNameConfirm(index, inputValues[index] || name)}
              className={styles.roleNameInput}
              prefix={
                <div
                  className={styles.roleNamePrefix}
                  style={{ backgroundColor: roleColors[index] }}
                />
              }
              suffix={<Image src={ICON_PATHS.EDIT_ICON} draggable={false} preview={false} />}
            />
          ))}
        </div>
      </div>
      <div className={styles.audioList}>
        {Array.from(uploadedAudioList).map((item, index) => (
          <div className={styles.audioItem} key={index}>
            <div className={styles.audioItemTitle}>
              <Image
                width={24}
                height={24}
                src={ICON_PATHS.MIC_ICON}
                draggable={false}
                preview={false}
              />
              <Select
                className={`${styles.select} ${styles.roleSelect}`}
                value={item.micType}
                onChange={value => handleMicTypeChange(index, value)}
                placeholder="未指定">
                {roleNames.map((name, index) => (
                  <Select.Option key={index} value={name}>
                    {name}
                  </Select.Option>
                ))}
              </Select>
            </div>
            <div className={styles.audioContent}>
              <MlsAudio
                src={item.url}
                title={item.name}
                progressHeight={20}
                showVolumeControl={false}
                progressBgColor="rgba(255, 255, 255, 0.2)"
                onOtherAction={handleDelete}
              />
            </div>
          </div>
        ))}
      </div>
      <MlsUpload
        action="/dk/v1/fileTransfer/uploader"
        accept="audio/*"
        maxSize={800}
        onSuccess={(result, file) => fileSuccess(result)}
        onError={(error, file) => fileUploadError({ file, error })}
        onRemove={percent => console.log('上传进度', percent)}></MlsUpload>
      <div className={styles.audioListFooter}>
        <Button onClick={handleMake} className={`${styles.saveBtn} button buttonPrimary`}>
          开始制作
        </Button>
      </div>
      {/* 新增：音频通道选择弹窗 */}
      <MlsModal
        title="音频信息"
        visible={showChannelModal}
        onConfirm={handleChannelConfirm}
        onCancel={() => setShowChannelModal(false)}
        modalProps={{
          width: 400,
          height: 300,
          className: `${styles.channelModal} custom-semi-modal-style`,
          maskClosable: false,
        }}
        footerContent={<span></span>}>
        <div className={styles.voiceDecodeBox}>
          {AUDIO_CHANNELS.map(channel => (
            <Button
              className={`button ${styles.voiceDecode}`}
              key={channel.value}
              value={channel.value}
              onClick={() => clickChannel(channel.value)}>
              {channel.label}
            </Button>
          ))}
        </div>
      </MlsModal>
    </div>
  );
}
